tx <- readRDS("temp/tx_submitters.rds") |>
  filter(!bad_counties2)

ballot_cols <- grep("^BallotType", names(tx))

# Iterate over the column indices
for (col_index in ballot_cols) {
  # Get the corresponding "Primary" column name
  primary_col <- sub("^BallotType_", "", names(tx)[col_index])
  
  # Replace values based on conditions
  tx[[col_index]][tx[[primary_col]] == "Y" & tx[[col_index]] == ""] <- "Unknown"
}

tx <- tx |> 
  mutate(across(starts_with("BallotType"), ~ case_when(. %in% c("Absentee", "Unknown") ~ .,
                                                       . == "" ~ "Did Not Vote",
                                                       T ~ "In Person")))

###################################

l_long <- pivot_longer(tx, cols = starts_with("BallotType_Gene"), names_to = "year", values_to = "turnout") |> 
  mutate(year = as.integer(substring(year, 20, 23)),
         vote_mode = turnout,
         turnout = vote_mode != "Did Not Vote")

ll <- l_long |> 
  group_by(treated = (app_rejected_sb1), year) |> 
  summarize(turnout = mean(turnout))

ll$treated <- factor(ll$treated, levels = c(F, T))
ll$treated <- ifelse(ll$treated == "TRUE", "Rejection", "No Rejection")

ggplot(filter(ll, year %% 4 == 2, year >= 2010), aes(x = year, y = turnout)) +
  geom_line(aes(linetype = treated), linewidth = 1) +
  geom_point(aes(shape = treated), size = 5) +
  theme_bc(base_size = 18, legend.position = "bottom",
           legend.text = element_text(size = 12),
           legend.title = element_text(size = 12)) +
  scale_linetype_manual(values = c("longdash", "solid")) +
  scale_y_continuous(labels = scales::percent) +
  scale_x_continuous(breaks = seq(2010, 2022, 4)) +
  geom_vline(xintercept = 2021.25, linetype = "solid", size = 1, color = "red") +
  annotate("text", x = 2019.5, y = 0.98, label = "2022 Primary", color = "black", size = 5) +
  labs(y = "Turnout",
       x = "Election",
       shape = "Treatment Status",
       linetype = "Treatment Status")

ggsave(paste0(out, "Figures/ts_app_rej.png"), width = 6, height = 4, units = "in")

l_long$treated <- (l_long$app_rejected_sb1)

l_long$t <- l_long$treated * (l_long$year > 2020)

m1 <- feols(turnout ~ t | LALVOTERID + year + Voters_FIPS, filter(l_long, year %% 4 == 2, year >= 2010))
m2 <- feols(turnout ~ t | LALVOTERID + year^Voters_FIPS, filter(l_long, year %% 4 == 2, year >= 2010))

#####
ll_b <- l_long |> 
  filter(ballot_submitted) |> 
  group_by(treated = (ballot_rejected_sb1), year) |> 
  summarize(turnout = mean(turnout))

ll_b$treated <- factor(ll_b$treated, levels = c(F, T))
ll_b$treated <- ifelse(ll_b$treated == "TRUE", "Rejection", "No Rejection")

ggplot(filter(ll_b, year %% 4 == 2, year >= 2010), aes(x = year, y = turnout)) +
  geom_line(aes(linetype = treated), linewidth = 1) +
  geom_point(aes(shape = treated), size = 5) +
  theme_bc(base_size = 18, legend.position = "bottom",
           legend.text = element_text(size = 12),
           legend.title = element_text(size = 12)) +
  scale_linetype_manual(values = c("longdash", "solid")) +
  scale_y_continuous(labels = scales::percent) +
  scale_x_continuous(breaks = seq(2010, 2022, 4)) +
  geom_vline(xintercept = 2021.25, linetype = "solid", size = 1, color = "red") +
  annotate("text", x = 2019.5, y = 0.98, label = "2022 Primary", color = "black", size = 5) +
  labs(y = "Turnout",
       x = "Election",
       shape = "Treatment Status",
       linetype = "Treatment Status")

ggsave(paste0(out, "Figures/ts_bal_rej.png"), width = 6, height = 4, units = "in")

ll <- bind_rows(ll |> 
                  mutate(group = "Application Rejected"),
                ll_b |> 
                  mutate(group = "Ballot Rejected"))

ggplot(filter(ll, year %% 4 == 2, year >= 2010), aes(x = year, y = turnout)) +
  facet_grid(. ~ group)  +
  geom_line(aes(linetype = treated), linewidth = 1) +
  geom_point(aes(shape = treated), size = 5) +
  theme_bc(legend.position = "bottom") +
  scale_linetype_manual(values = c("longdash", "solid")) +
  scale_y_continuous(labels = scales::percent) +
  scale_x_continuous(breaks = seq(2010, 2022, 4)) +
  geom_vline(xintercept = 2021.25, linetype = "solid", size = 1, color = "red") +
  annotate("text", x = 2018.8, y = 0.98, label = "2022 Primary", color = "black") +
  labs(y = "Turnout",
       x = "Election",
       shape = "Treatment Status",
       linetype = "Treatment Status",
       caption = "'Application Rejected' panel includes all individuals who submitted a mail ballot application for the 2022 primary. 'Ballot Rejected' panel includes those who submitted a mail ballot in the 2022 primary.
In all cases, 'No Rejection' refers to voters who did not have an application or ballot rejected in the primary of 2022; the inverse is true for the 'Rejection' voters. In other words, these groups remain constant across time.")
ggsave(paste0(out, "Figures/total_rej_fig_gen.png"), width = 6, height = 4, units = "in")
################################
l_long$treated <- (l_long$ballot_rejected_sb1)

l_long$t <- l_long$treated * (l_long$year > 2020)

m3 <- feols(turnout ~ t | LALVOTERID + year + Voters_FIPS, filter(l_long, year %% 4 == 2, ballot_submitted, year >= 2010))
m4 <- feols(turnout ~ t | LALVOTERID + year ^ Voters_FIPS, filter(l_long, year %% 4 == 2, ballot_submitted, year >= 2010))

rows <- tribble(~term,          ~m1,  ~m2, ~m3, ~m4,
                "Voter Fixed Effects", "$\\checkmark$", "$\\checkmark$", "$\\checkmark$", "$\\checkmark$",
                "Year Fixed Effects", "$\\checkmark$", "", "$\\checkmark$", "",
                "County Fixed Effects", "$\\checkmark$", "", "$\\checkmark$", "",
                "County-Year Fixed Effects", "", "$\\checkmark$", "", "$\\checkmark$")

attr(rows, 'position') <- c(3:6)

modelsummary(list(m1, m2, m3, m4),
             statistic = "std.error",
             stars = c("*" = 0.05, "**" = 0.01, "***" = 0.001),
             coef_map = c("t" = "Treated × 2022"),
             add_rows = rows,
             notes = list("Standard errors clustered by individual.",
                          "Includes 2010--2022 midterm general elections."),
             gof_omit = 'DF|Deviance|AIC|BIC|Within|Pseudo|Log|Std|FE|RMSE',
             title = "\\label{tab:did-reg} Effect of a Primary Rejection on General Turnout",
             output = "latex",
             escape = FALSE) |> 
  add_header_above(c(" " = 1, "Application Rejected" = 2, "Ballot Rejected" = 2), align = "c") |> 
  # kable_styling(latex_options="scale_down") |> 
  save_kable(paste0(out, "Tables/did_reg.tex"))


l_long$time_to_treat <- l_long$year - 2022

m2 <- feols(turnout ~ i(time_to_treat, app_rejected_sb1, ref = -4) | LALVOTERID + year ^ Voters_FIPS, filter(l_long, year %% 4 == 2, year >= 2010))
m4 <- feols(turnout ~ i(time_to_treat, ballot_rejected_sb1, ref = -4) | LALVOTERID + year ^ Voters_FIPS, filter(l_long, year %% 4 == 2, ballot_submitted, year >= 2010))

output <- rbindlist(lapply(list(m2, m4), function(mod){

  cints <- confint(mod) |> 
    rename(lb = `2.5 %`, ub = `97.5 %`) |> 
    mutate(year = c(2010, 2014, 2022),
           est = (lb + ub) / 2)
  
  cints$g <- ifelse(grepl("app", rownames(cints)), "app", "ballot")
  return(cints)
}))

output <- bind_rows(output,
                    data.table(year = c(2018, 2018),
                               est = 0,
                               g = c("app", "ballot"))) |> 
  mutate(c = factor(ifelse(year == 2022, "Post-Treatment", "Pre-Treatment"),
                    levels = c("Pre-Treatment", "Post-Treatment")))

ggplot(filter(output, g == "app"), aes(x = year, y = est, ymax = ub, ymin = lb, color = c)) +
  geom_point() +
  theme_bc() +
  geom_errorbar(width = 0) +
  scale_color_manual(values = c("black", "red")) +
  geom_vline(xintercept = 2018, linetype = "dashed") +
  geom_hline(yintercept = 0, linetype = "solid") +
  scale_x_continuous(breaks = seq(2010, 2022, 4)) +
  scale_y_continuous(labels = percent) +
  labs(x = "Year", y = "Estimated Treatment Effect", color = "",
       caption = "All years measured relative to 2018 (final pre-treatment midterm election). Includes voter and county-year fixed effects. Standard errors clustered by voter.")
ggsave(paste0(out, "Figures/did_general_app.png"), width = 6, height = 4, units = "in")

ggplot(filter(output, g == "ballot"), aes(x = year, y = est, ymax = ub, ymin = lb, color = c)) +
  geom_point() +
  theme_bc() +
  geom_errorbar(width = 0) +
  scale_color_manual(values = c("black", "red")) +
  geom_vline(xintercept = 2018, linetype = "dashed") +
  geom_hline(yintercept = 0, linetype = "solid") +
  scale_x_continuous(breaks = seq(2010, 2022, 4)) +
  scale_y_continuous(labels = percent) +
  labs(x = "Year", y = "Estimated Treatment Effect", color = "",
       caption = "All years measured relative to 2018 (final pre-treatment midterm election). Includes voter and county-year fixed effects. Standard errors clustered by voter.")
ggsave(paste0(out, "Figures/did_general_ballot.png"), width = 6, height = 4, units = "in")

##################################
cleanup("l_long")

ll <- l_long |> 
  filter(!(vote_mode %in% c("Did Not Vote", "Unknown"))) |> 
  group_by(treated = (app_rejected_sb1), year, vote_mode) |> 
  tally() |> 
  group_by(treated, year) |> 
  mutate(turnout = n / sum(n))

ll$treated <- factor(ll$treated, levels = c(F, T))
ll$treated <- ifelse(ll$treated == "TRUE", "Rejection", "No Rejection")

ll_b <- l_long |> 
  filter(ballot_submitted, !(vote_mode %in% c("Did Not Vote", "Unknown"))) |>
  group_by(treated = (ballot_rejected_sb1), year, vote_mode) |> 
  tally() |> 
  group_by(treated, year) |> 
  mutate(turnout = n / sum(n))

ll_b$treated <- factor(ll_b$treated, levels = c(F, T))
ll_b$treated <- ifelse(ll_b$treated == "TRUE", "Rejection", "No Rejection")


ll <- bind_rows(ll |> 
                  mutate(group = "Application Rejected"),
                ll_b |> 
                  mutate(group = "Ballot Rejected"))

ggplot(filter(ll, year %% 4 == 2, year >= 2010, vote_mode == "In Person"), aes(x = year, y = turnout)) +
  facet_grid(vote_mode ~ group)  +
  geom_line(aes(linetype = treated), linewidth = 1) +
  geom_point(aes(shape = treated), size = 5) +
  theme_bc(legend.position = "bottom") +
  scale_linetype_manual(values = c("longdash", "solid")) +
  scale_y_continuous(labels = scales::percent, limits = c(0, 1)) +
  scale_x_continuous(breaks = seq(2010, 2022, 4)) +
  geom_vline(xintercept = 2021.125, linetype = "solid", size = 1, color = "red") +
  annotate("text", x = 2018.5, y = 1, label = "2022 Primary", color = "black") +
  labs(y = "Turnout",
       x = "Election",
       shape = "Treatment Status",
       linetype = "Treatment Status",
       caption = "'Application Rejected' panel includes all individuals who submitted a mail ballot application for the 2022 primary. 'Ballot Rejected' panel includes those who submitted a mail ballot in the 2022 primary.
In all cases, 'No Rejection' refers to voters who did not have an application or ballot rejected in the primary of 2022; the inverse is true for the 'Rejection' voters. In other words, these groups remain constant across time.")

ggsave(paste0(out, "Figures/rej_behav.png"), width = 6, height = 4, units = "in")

##################################
cleanup("l_long")

l_long_v <- filter(l_long, !(vote_mode %in% c("Did Not Vote", "Unknown")))

l_long_v$treated <- (l_long_v$app_rejected_sb1)

l_long_v$t <- l_long_v$treated * (l_long_v$year > 2020)

m1 <- feols((vote_mode == "In Person") ~ t | LALVOTERID + year + Voters_FIPS, filter(l_long_v, year %% 4 == 2, year >= 2010))
m2 <- feols((vote_mode == "In Person") ~ t | LALVOTERID + year^Voters_FIPS, filter(l_long_v, year %% 4 == 2, year >= 2010))

l_long_v$treated <- (l_long_v$ballot_rejected_sb1)

l_long_v$t <- l_long_v$treated * (l_long_v$year > 2020)

m3 <- feols((vote_mode == "In Person") ~ t | LALVOTERID + year + Voters_FIPS, filter(l_long_v, year %% 4 == 2, ballot_submitted, year >= 2010))
m4 <- feols((vote_mode == "In Person") ~ t | LALVOTERID + year ^ Voters_FIPS, filter(l_long_v, year %% 4 == 2, ballot_submitted, year >= 2010))

rows <- tribble(~term,          ~m1,  ~m2, ~m3, ~m4,
                "Voter Fixed Effects", "$\\checkmark$", "$\\checkmark$", "$\\checkmark$", "$\\checkmark$",
                "Year Fixed Effects", "$\\checkmark$", "", "$\\checkmark$", "",
                "County Fixed Effects", "$\\checkmark$", "", "$\\checkmark$", "",
                "County-Year Fixed Effects", "", "$\\checkmark$", "", "$\\checkmark$")

attr(rows, 'position') <- c(3:6)

modelsummary(list(m1, m2, m3, m4),
             statistic = "std.error",
             stars = c("*" = 0.05, "**" = 0.01, "***" = 0.001),
             coef_map = c("t" = "Treated × 2022"),
             add_rows = rows,
             notes = list("Standard errors clustered by individual.",
                          "Includes 2010--2022 midterm general elections."),
             gof_omit = 'DF|Deviance|AIC|BIC|Within|Pseudo|Log|Std|FE|RMSE',
             title = "\\label{tab:did-reg-behave} Effect of a Primary Rejection on Voting In-Person in General (Conditional on Voting)",
             output = "latex",
             escape = FALSE) |> 
  add_header_above(c(" " = 1, "Application Rejected" = 2, "Ballot Rejected" = 2), align = "c") |> 
  # kable_styling(latex_options="scale_down") |> 
  save_kable(paste0(out, "Tables/did_reg_vm.tex"))

l_long_v$time_to_treat <- l_long_v$year - 2022

m2 <- feols((vote_mode == "In Person") ~ i(time_to_treat, app_rejected_sb1, ref = -4) | LALVOTERID + year ^ Voters_FIPS, filter(l_long_v, year %% 4 == 2, year >= 2010))
m4 <- feols((vote_mode == "In Person") ~ i(time_to_treat, ballot_rejected_sb1, ref = -4) | LALVOTERID + year ^ Voters_FIPS, filter(l_long_v, year %% 4 == 2, ballot_submitted, year >= 2010))

output <- rbindlist(lapply(list(m2, m4), function(mod){
  
  cints <- confint(mod) |> 
    rename(lb = `2.5 %`, ub = `97.5 %`) |> 
    mutate(year = c(2010, 2014, 2022),
           est = (lb + ub) / 2)
  
  cints$g <- ifelse(grepl("app", rownames(cints)), "app", "ballot")
  return(cints)
}))

output <- bind_rows(output,
                    data.table(year = c(2018, 2018),
                               est = 0,
                               g = c("app", "ballot"))) |> 
  mutate(c = factor(ifelse(year == 2022, "Post-Treatment", "Pre-Treatment"),
                    levels = c("Pre-Treatment", "Post-Treatment")))

ggplot(filter(output, g == "app"), aes(x = year, y = est, ymax = ub, ymin = lb, color = c)) +
  geom_point() +
  theme_bc() +
  geom_errorbar(width = 0) +
  scale_color_manual(values = c("black", "red")) +
  geom_vline(xintercept = 2018, linetype = "dashed") +
  geom_hline(yintercept = 0, linetype = "solid") +
  scale_x_continuous(breaks = seq(2010, 2022, 4)) +
  scale_y_continuous(labels = percent) +
  labs(x = "Year", y = "Estimated Treatment Effect", color = "",
       caption = "All years measured relative to 2018 (final pre-treatment midterm election). Includes voter and county-year fixed effects. Standard errors clustered by voter.")
ggsave(paste0(out, "Figures/did_general_app_in_person.png"), width = 6, height = 4, units = "in")

ggplot(filter(output, g == "ballot"), aes(x = year, y = est, ymax = ub, ymin = lb, color = c)) +
  geom_point() +
  theme_bc() +
  geom_errorbar(width = 0) +
  scale_color_manual(values = c("black", "red")) +
  geom_vline(xintercept = 2018, linetype = "dashed") +
  geom_hline(yintercept = 0, linetype = "solid") +
  scale_x_continuous(breaks = seq(2010, 2022, 4)) +
  scale_y_continuous(labels = percent) +
  labs(x = "Year", y = "Estimated Treatment Effect", color = "",
       caption = "All years measured relative to 2018 (final pre-treatment midterm election). Includes voter and county-year fixed effects. Standard errors clustered by voter.")
ggsave(paste0(out, "Figures/did_general_ballot_in_person.png"), width = 6, height = 4, units = "in")

